package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = {"com.atguigu.gulimall.product.controller"})
@RestControllerAdvice(basePackages = {"com.atguigu.gulimall.product.controller"})
//@RestControllerAdvice ===> ControllerAdvice+ResponseBody
public class GulimallExceptionControllerAdvice {

    //@ResponseBody 注解标注在类上
//    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
//        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> errorInfo = new HashMap<>();
            result.getFieldErrors().forEach(error -> {
                //获取错误的属性的名字
                String fieldName = error.getField();
                //FieldError 获取到错误提示
                String message = error.getDefaultMessage();
                errorInfo.put(fieldName, message);
            });
            //获取校验的错误结果
            return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data", errorInfo);
        }
        return R.error();
    }

    @ExceptionHandler({Exception.class})
//    public R handleException(Exception e) {
    public R handleException(Throwable throwable) {
//        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
//        log.error("错误：", e);
        log.error("错误：", throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
